// =======================================================================
// 
//       Filename:  plugin.cpp
// 
//    Description:  
// 
//        Version:  1.0
//        Created:  27.03.2010 18:09:38
//       Revision:  none
//       Compiler:  g++
// 
//         Author:  Dominik 'domachine' Burgdörfer (-), dominik.burgdoerfer@googlemail.com
//        Company:  -
// 
// =======================================================================

#include "plugin.hpp"
#include <dlfcn.h>
#include "citerator.hpp"

namespace webplodder {
    Plugin::Plugin(const boost::filesystem::path& file) 
        : mhandle(0),
          mPluginObject(0), mPath(file)
    {
    }

    Plugin::~Plugin() {
        close();
    }

    void Plugin::open()
    {
        if(mhandle != 0)
            return;

        mhandle = dlopen(mPath.string().c_str(), RTLD_LAZY);
        if(!mhandle)
            throw std::runtime_error(dlerror());

        typedef PluginObject* (*NewInstancePtr)();

        NewInstancePtr pN;

        void* pSymbol = dlsym(mhandle, "newInstance");
        if(!pSymbol)
            throw std::runtime_error(dlerror());

        pN = (NewInstancePtr)(pSymbol);
        
        mPluginObject = (*pN)();
    }

    void Plugin::close()
    {
        if(mPluginObject)
            delete mPluginObject;

        if(mhandle)
            if(dlclose(mhandle) != 0)
                throw std::runtime_error(dlerror());
    }

    std::string Plugin::name() const
       
    {
        return mPath.stem();
    }

    void Plugin::call(PageMap& pagemap, std::ostream& oStream,
                      const std::vector<boost::any>& args)
    {
        mPluginObject->launch(pagemap, oStream, args);
        //(*mpluginCallback)(pagemap, oStream, args);
    }
}
